import {
	CART_LIST,
	CHECK_ALL,
	UN_CHECK_ALL,
	CHECK_ITEM
	} from './mutations-types.js'
	
import { Toast,Dialog  } from 'vant';
import http from '@/common/api/request.js'

export default{
	state:{
		list:[],//购物车的数据
		selectList:[]//选中的数据
	},
	getters:{
		//全选判断
		isCheckAll(state){
			return state.list.length == state.selectList.length
		},
		//计算算总价
		total(state){
			//计算量
			let total={
				   num:0,
				   price:0
			    }
				
			//遍历--相加
			state.list.forEach(item =>{
				// console.log(tiem)
				if(item.checked){ //选中时checked为true
					total.num += parseInt(item.goods_num);
					total.price += item.goods_price * item.goods_num;
				}
			})
			return total;
		}
	},
	mutations:{
		[CART_LIST](state, carArr){
			// console.log(carArr)
			state.list = carArr
			
			//buy导致进入购物车页面就执行push,
			// carArr.forEach(item=>{
			// 	state.selectList.push( item.id )
			// })
			//修正
			state.selectList = state.list.map(item =>{
				return item.id
			})
			
		},
		
		//全选
		[CHECK_ALL](state){
			state.selectList = state.list.map(item =>{
				item.checked = true;
				return item.id
			})
		},
		//全不选
		[UN_CHECK_ALL](state){
			state.list.forEach(item=>{
				item.checked = false;
			})
			//清空选中的数据
			state.selectList = []
		},
		
		//单选
		[CHECK_ITEM](state, index){
			let id = state.list[index].id;
			let i= state.selectList.indexOf(id);
			
			if(i > -1){//能在selectList找到对应的id，就删除
				return state.selectList.splice(i,1)
			}
			//如果之前没有选择中，就给selectLIst添加一个id进去
			 state.selectList.push(id)
		},
		
		//删除（更新）保存在购物车里的原有数据
		delGoods( state ){
			state.list = state.list.filter(item =>{
				return state.selectList.indexOf(item.id) == -1
			})
		}
	},
	actions:{
		//购物车选中状态
		checkAllFn({commit, getters}){
			getters.isCheckAll ? commit('UnCheckAll') : commit('checkAll')
		},
		//商品删除操作
		delGoodsFn({commit, state}, id){
			// alert(state.selectList.length == 0)
			
			let arrCart = []
			   //如果无商品被选中则提示信息
			   if(state.selectList.length == 0){
			   	Toast('提示内容');
				 // return
			   }
			   
			  
			   
			   Dialog.confirm({
			     message:'确定要删除这些商品码？',
			   }).then(() => {
				   if(typeof id == "number"){
				   		 //单选删除
				   		 arrCart = [id]
				   		 let index = state.list.findIndex(item=>{
				   		   return item.id = id
				   		 })
				   		 state.list.splice(index,1)
				   }else{
				   		  //多选删除
				   		  arrCart = state.selectList
				   		  //删除（更新）保存在购物车里的原有数据
				   		  commit("delGoods");
				   		  //全不选
				   		  commit('UnCheckAll');
				   }
				   
			       http.$axios({
					   url:'/api/deleteCart',
					   method:'post',
					   data:{
						   arrId:arrCart
					   }
				   }).then(res=>{
					  
					   //获取数据库购物车的剩余数据
					   // state.list = res.data
					  
					   //提示
					   if(res.success){
						   Toast(res.msg)
					   }
				   })
			     })
		},
	}
}